<?php

namespace app\index\controller;

use think\Controller;
use think\Request;

class User extends Controller
{
	// 肿瘤防治健康跑
	// https://jiankangpao.sichuancancer.org/myadmin/index.php
	// https://jiankangpao.sichuancancer.org/azfzjkp/home/login/login.html
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/home/login/login1.html
	// http://192.168.8.130/azfzjkp_dev/home/login/login1.html
	// admin azfzjkp-a

	protected $appId = "wx65e037fa4769e325";
	protected $appSecret = "8501716cff7129294bc478070930067d";

	protected $cacheTime = 10; //缓存时间（秒）
	protected $onePage = 20; // 每页数量
	protected $userInfo;
	protected $httpReferer;

	protected $letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

	protected $regionList = [
		[
			'name' => '成都市',
			'x' => 405,
			'y' => 425,
			'finished' => 'no'
		],
		[
			'name' => '德阳市',
			'x' => 396,
			'y' => 308,
			'finished' => 'no'
		],
		[
			'name' => '绵阳市',
			'x' => 463,
			'y' => 308,
			'finished' => 'no'
		],
		[
			'name' => '自贡市',
			'x' => 432,
			'y' => 581,
			'finished' => 'no'
		],
		[
			'name' => '攀枝花',
			'x' => 204,
			'y' => 904,
			'finished' => 'no'
		],
		[
			'name' => '泸州市',
			'x' => 531,
			'y' => 641,
			'finished' => 'no'
		],
		[
			'name' => '广元市',
			'x' => 552,
			'y' => 189,
			'finished' => 'no'
		],
		[
			'name' => '遂宁市',
			'x' => 515,
			'y' => 426,
			'finished' => 'no'
		],
		[
			'name' => '内江市',
			'x' => 480,
			'y' => 539,
			'finished' => 'no'
		],
		[
			'name' => '乐山市',
			'x' => 320,
			'y' => 602,
			'finished' => 'no'
		],
		[
			'name' => '南充市',
			'x' => 568,
			'y' => 355,
			'finished' => 'no'
		],
		[
			'name' => '宜宾市',
			'x' => 455,
			'y' => 690,
			'finished' => 'no'
		],
		[
			'name' => '广安市',
			'x' => 621,
			'y' => 441,
			'finished' => 'no'
		],
		[
			'name' => '达州市',
			'x' => 693,
			'y' => 354,
			'finished' => 'no'
		],
		[
			'name' => '巴中市',
			'x' => 636,
			'y' => 265,
			'finished' => 'no'
		],
		[
			'name' => '雅安市',
			'x' => 273,
			'y' => 457,
			'finished' => 'no'
		],
		[
			'name' => '眉山市',
			'x' => 376,
			'y' => 529,
			'finished' => 'no'
		],
		[
			'name' => '资阳市',
			'x' => 443,
			'y' => 447,
			'finished' => 'no'
		],
		[
			'name' => '阿坝州',
			'x' => 263,
			'y' => 206,
			'finished' => 'no'
		],
		[
			'name' => '甘孜州',
			'x' => 68,
			'y' => 374,
			'finished' => 'no'
		],
		[
			'name' => '凉山州',
			'x' => 247,
			'y' => 732,
			'finished' => 'no'
		],
	];

	protected $beforeActionList = [
		'first'		=> ['except' => 'show,asReport,toLogin,msgSecCheck,showConfig,todo,test0362'], // 这些方法不执行前置方法
		'second'	=> ['only' => 'qa'],
	];

	protected function _initialize()
	{
		parent::_initialize();

		// 分解微信小程序的HTTP_REFERER，里面包含了appid以及小程序版本号
		$this->httpReferer = explode("/", input('server.HTTP_REFERER'));
	}

	// 前置方法
	protected function first()
	{
		$request = Request::instance();
		$baseUrl = $request->baseUrl();

		// 1.判断微信小程序的HTTP_REFERER中的appid
		// if (empty($this->httpReferer[3]) || $this->appId != $this->httpReferer[3]) {
		// 	echo "Are you ok?";
		// 	exit;
		// }
		// $form_time_line = input('form_time_line/s');
		// if ($form_time_line) {
		// 	return;
		// }

		// 2.判断访问请求的合法性
		$secretKey = 'my9527azfzjkp';
		$timestamp = input('timestamp/s');
		$token = input('token/s');
		$openid = input('openid/s');
		// 2.1判断token是否正确
		if ($token != md5($timestamp . $secretKey . $openid)) {
			echo json_encode(array('code' => '-1', 'msg' => "参数异常，请重新登录！"));
			exit;
		}

		// 2.2判断时间是否过期
		if (time() - $timestamp > 300) {
			echo json_encode(array('code' => '-2', 'msg' => "参数过期，请重新请求！" . time() . "-" . $timestamp));
			exit;
		}

		// 3.判断该用户是否存在
		$openid = input('openid/s');
		$userInfo = db("user_info")->where("openid = '{$openid}'")->find();
		if (empty($userInfo)) {
			echo json_encode(array('code' => '-3', 'msg' => "未登录，请先登录！"));
			exit;
		} else if ($userInfo['limit_time'] > date('Y-m-d H:i:s')) {
			echo json_encode(array('code' => '-3', 'msg' => "对不起，到{$userInfo['limit_time']}前您暂不能使用！"));
			exit;
		}

		$this->userInfo = $userInfo;
	}

	// 前置方法
	protected function second()
	{
		$data['last_login'] = date('Y-m-d H:i:s');
		db("user_info")->where("id = '{$this->userInfo['id']}'")->update($data);
	}

	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/User/test0362.html
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/Index/User/test0362.html
	// http://192.168.8.130/azfzjkp_dev/Index/User/test0362.html
	public function test0362()
	{
		$request = Request::instance();
		// 获取URL访问的ROOT地址
		$domain = $request->domain();
		var_dump($domain);
		$client_ip = $request->ip();
		var_dump($client_ip);
		die();
	}

	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/Index/User/formula.html?formula=%2850%2B10%2A%281%20-%2013.49%29%29%2F3.02
	// public function formula()
	// {
	// 	$formula = input('formula/s');
	// 	$formula = rawurldecode($formula);
	// 	echo "<script type='text/javascript'> document.write(eval('{$formula}')); </script>";
	// }

	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/User/showConfig/type/faq.html
	public function showConfig()
	{
		$type = trim(input('type/s')); //faq 常见题目 nda 用户协议
		$configs = db("configs")->where("name = '{$type}'")->find();
		$configs['value'] = htmlspecialchars_decode($configs['value']);

		$this->assign('configs', $configs);
		return $this->fetch();
	}

	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/user/toLogin.html?code=xxxx
	// 1.登录
	public function toLogin()
	{
		$code = input('code/s');
		$url =  "https://api.weixin.qq.com/sns/jscode2session?appid={$this->appId}&secret={$this->appSecret}&js_code={$code}&grant_type=authorization_code";

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$result = curl_exec($ch);
		if (curl_errno($ch)) {
			return json(array('code' => '1', 'msg' => "登录失败，请稍后再试。", 'result' => $result));
		}
		curl_close($ch);

		$info = json_decode($result, true);
		if (empty($info['openid'])) {
			return json(array('code' => '2', 'msg' => "登录失败，请稍后再试！", 'result' => $result));
		}

		// 保存数据库
		$userInfo = db("user_info")
			->field("id,openid,phone,avatar_img,nick_name,true_name,birthday,job,status")
			->where("openid = '{$info['openid']}'")
			->find();

		if (empty($userInfo)) {
			$userInfo['openid'] = $info['openid'];
			$userInfo['session_key'] = $info['session_key'];
			$userInfo['update_time'] = date('Y-m-d H:i:s');

			$userInfo['status'] = 1; // 0:不可用 1:可用只取得id 2:可用已取得昵称头像
			$userInfo['id'] = db("user_info")->insert($userInfo);
		} else {
			$userInfo['session_key'] = $info['session_key'];
			$userInfo['update_time'] = date('Y-m-d H:i:s');
			db("user_info")->where("openid = '{$info['openid']}'")->update($userInfo);
		}

		// 1.判断微信小程序的HTTP_REFERER中的appid
		$version = isset($this->httpReferer[4]) ? $this->httpReferer[4] : "";
		// 开发者工具中，为devtools，开发版及体验版为0，正式版则为1，这样就能区分运行环境了。
		if (
			$version == "全部到正式"
			|| $version == "devtools" // 开发者工具
			// || $version == 0 // 开发版及体验版为0
			// || $info['openid'] == 'oFle76_Y1lv-QMqtU9FXSGTFDMUc' //小林
			// || $info['openid'] == 'oyKKk65fBqXUpmbWFMQfY6-D7p8M' //丫丫
		) {
			// $baseUrl = "http://192.168.8.130/azfzjkp_dev";
			$baseUrl = "https://jiankangpao.sichuancancer.org/azfzjkp_dev";
		} else {
			$baseUrl = "https://jiankangpao.sichuancancer.org/azfzjkp";
		}

		// 2.判断是否已经参加过
		$userInfo['as_record_count'] = db("as_record")->where("openid = '{$info['openid']}'")->count();

		$userInfo['baseUrl'] = $baseUrl;

		return json(array('code' => '0', 'msg' => "登录成功！", 'info' => $userInfo, 'version' => $version, 'version' => $version));
	}

	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/user/setUserInfo.html?openid=oaKIUt1XRrjyUpvJv8W0sYZlD5Bs&avatar_img=avatar_img.png&nick_name=name
	// 2.小程序用户登录
	// public function setUserInfo()
	// {
	// 	$openid = input('openid/s');
	// 	$todo = input('todo/s');

	// 	$info['openid'] = $openid;
	// 	$info['avatar_img'] = input('avatar_img/s');
	// 	$info['phone'] = input('phone/s');
	// 	$info['nick_name'] = input('nick_name/s');
	// 	if ($todo == 'edit') {
	// 		$info['true_name'] = input('true_name/s');
	// 		$info['birthday'] = input('birthday/s');
	// 		$info['job'] = input('job/s');
	// 	}

	// 	$userInfo = db("user_info")->where("openid = '{$openid}'")->find();

	// 	// 判断手机号是否被使用
	// 	$where = [];
	// 	$where['phone'] = $info['phone'];
	// 	$where['id'] = ['<>', $userInfo['id']];
	// 	$res = db('user_info')->where($where)->find();
	// 	if (!empty($res)) {
	// 		if (empty($userInfo)) {
	// 			// 小程序openid取得为空，就是使用手机号取得的记录
	// 			$userInfo = $res;
	// 		} else if ($res['id'] != $userInfo['id']) {
	// 			// 小程序openid取得的和手机号取得的不一致，合并数据，并删除openid取得的
	// 			db('user_info')->where('id', $userInfo['id'])->delete();
	// 			$userInfo = $res;
	// 		}
	// 	}

	// 	if (!empty($info['birthday'])) {
	// 		$info['birthday'] = $info['birthday'] ? $info['birthday'] : null;
	// 		$info['birthday'] = $info['birthday'] != 'null' ? $info['birthday'] : null;
	// 		$info['birthday'] = $info['birthday'] != 'undefined' ? $info['birthday'] : null;
	// 	}

	// 	// 保存数据库
	// 	if (empty($userInfo)) {
	// 		$info['update_time'] = date('Y-m-d H:i:s');
	// 		$info['status'] = 2; // 0:不可用 1:可用只取得id 2:可用已取得昵称头像
	// 		$info['id'] = db("user_info")->insert($info);
	// 	} else {
	// 		$info['update_time'] = date('Y-m-d H:i:s');
	// 		$info['status'] = 2; // 0:不可用 1:可用只取得id 2:可用已取得昵称头像
	// 		db("user_info")->where("id", $userInfo['id'])->update($info);

	// 		if ($todo != 'edit') {
	// 			$info['true_name'] = $userInfo['true_name'];
	// 			$info['birthday'] = $userInfo['birthday'];
	// 			$info['job'] = $userInfo['job'];
	// 		}
	// 	}

	// 	return json(array('code' => '0', 'msg' => "保存成功！", 'info' => $info)); //, 'res' => $res, 'sql' => $sql
	// }

	// 生成登录二维码
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/Index/user/getLoginQrcode.html?loginCode=230518-100511393
	// public function getLoginQrcode()
	// {
	// 	$loginCode = input('loginCode');

	// 	$ACCESS_TOKEN = $this->getAccessToken();
	// 	$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN;

	// 	//要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
	// 	$request = Request::instance();
	// 	// 获取URL访问的ROOT地址
	// 	$root = $request->root();

	// 	// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
	// 	if ($root == '/azfzjkp_dev') {
	// 		// 开发环境
	// 		$env_version = 'trial'; //体验版
	// 	} else {
	// 		// 生产环境
	// 		$env_version = 'release'; //正式版
	// 	}

	// 	$post_data = array(
	// 		"page" => "pages/index/index",
	// 		"scene" => "login?c=" . $loginCode,
	// 		"env_version" => $env_version,
	// 		"check_path" => false,
	// 		'is_hyaline' => true,
	// 		'width' => 280
	// 	);

	// 	$post_data = json_encode($post_data);
	// 	$data = http_request($url, $post_data);

	// 	header("content-type:image/png;");
	// 	echo $data;
	// 	return;
	// }

	// 生成二维码
	// https://jiankangpao.sichuancancer.org/azfzjkp_dev/Index/user/getQrcode.html?qa_main_id=94&doctor_id=1&price=2
	// public function getQrcode()
	// {
	// 	$qa_main_id = input('qa_main_id');
	// 	$as_order_id = input('as_order_id');

	// 	$ACCESS_TOKEN = $this->getAccessToken();
	// 	$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $ACCESS_TOKEN;

	// 	//要打开的小程序版本。正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
	// 	$request = Request::instance();
	// 	// 获取URL访问的ROOT地址
	// 	$root = $request->root();

	// 	// 正式版为 "release"，体验版为 "trial"，开发版为 "develop"。默认是正式版。
	// 	if ($root == '/azfzjkp_dev') {
	// 		// 开发环境
	// 		$env_version = 'trial'; //体验版
	// 	} else {
	// 		// 生产环境
	// 		$env_version = 'release'; //正式版
	// 	}

	// 	$post_data = array(
	// 		"page" => "pages/index/index",
	// 		"scene" => "detail?q_d=" . $qa_main_id . "&a_d=" . $as_order_id,
	// 		"env_version" => $env_version,
	// 		"check_path" => false,
	// 		'is_hyaline' => true,
	// 		'width' => 280
	// 	);

	// 	$post_data = json_encode($post_data);
	// 	$data = http_request($url, $post_data);

	// 	header("content-type:image/png;");
	// 	echo $data;
	// 	return;
	// }

	//解密手机号
	// public function getPhoneNumber()
	// {
	// 	$openid = input('openid/s');
	// 	if (empty($openid)) {
	// 		return json(array('code' => '-1', 'msg' => "未获取到openid！"));
	// 	}
	// 	$encryptedData = input('encryptedData/s');
	// 	$iv = input('iv/s');

	// 	//解密手机号
	// 	$result = openssl_decrypt(base64_decode($encryptedData), "AES-128-CBC", base64_decode($this->userInfo['session_key']), 1, base64_decode($iv));
	// 	$phoneData = json_decode($result, true);
	// 	$phone = $phoneData['phoneNumber'];
	// 	if (empty($phone)) {
	// 		return json(array('code' => '-2', 'msg' => "session_key过期！" . $this->userInfo['session_key'], array('userInfo' => $this->userInfo)));
	// 	}

	// 	db("user_info")->where('openid', $openid)->update(array('phone' => $phone));

	// 	return json(array('code' => '0', 'msg' => "保存成功！", 'data' => ['openid' => $openid, 'phone' => $phone]));
	// }

	//二进制转图片
	// public function data_uri($contents, $mime)
	// {
	// 	$base64   = base64_encode($contents);
	// 	return ('data:' . $mime . ';base64,' . $base64);
	// }

	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/user/msgSecCheck.html?msg=特3456书yuuo莞6543李zxcz蒜7782法fgnv级
	// 违规文字检测
	protected function msgSecCheck($msg)
	{
		// public function msgSecCheck(){
		// 	$msg = input('msg/s');

		$ACCESS_TOKEN = $this->getAccessToken();
		// var_dump($ACCESS_TOKEN);
		$url =  "https://api.weixin.qq.com/wxa/msg_sec_check?access_token={$ACCESS_TOKEN}";
		$data_string = '{"content": "' . $msg . '"}';

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt(
			$ch,
			CURLOPT_HTTPHEADER,
			array(
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string)
			)
		);

		$result = curl_exec($ch);
		if (curl_errno($ch)) {
			return json(array('errcode' => '0', 'msg' => "违规文字检测失败"));
		}
		curl_close($ch);

		$info = json_decode($result, true);
		// var_dump($info);
		return $info;
	}

	// https://jiankangpao.sichuancancer.org/azfzjkp/Index/user/getAccessToken.html
	// 取得调用接口凭证（后台用的AccessToken）
	private function getAccessToken()
	{
		// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
		$cacheKey = md5('access_token_' . $this->appId);
		$accessToken = cache($cacheKey);
		if (empty($accessToken)) {
			$url =  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" .
				"&appid=" . $this->appId .
				"&secret=" . $this->appSecret;

			$content = file_get_contents($url);
			$info = json_decode($content);

			$accessToken = $info->access_token;
			cache($cacheKey, $accessToken, 3 * 60); //3分钟
		}
		return $accessToken;
	}
}
